package com.example.intelligentattendancesystem.controller.interceptor;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.*;

@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor(stringRedisTemplate)).excludePathPatterns(
                "/smartAttendance/index/login",
                "/smartAttendance/index/register",
                "/error",
                "/static/**"
        );
        WebMvcConfigurer.super.addInterceptors(registry);
    }
    public void downloadFile(@RequestParam("filename") String filename, HttpServletResponse response) {
        // 假设文件存储在固定目录下的files文件夹中
        String directory = "/path/to/your/files/"; // 替换为你的文件目录
        String filePath = directory + filename; // 使用传入的文件名拼接出完整的文件路径

        File file = new File(filePath);
        if (!file.exists()) {
            // 如果文件不存在，返回404状态码
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentLength((int) file.length());

        try {
            try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 发生错误时的处理
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("文件下载失败");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
